package com.zretc.emptraining.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.emptraining.dao.EmpDao;
import com.zretc.emptraining.dao.UsersDao;
import com.zretc.emptraining.daoimpl.EmpDaoImpl;
import com.zretc.emptraining.daoimpl.UsersDaoImpl;
import com.zretc.emptraining.dbtools.DBTools;
import com.zretc.emptraining.dbtools.ITransaction;
import com.zretc.emptraining.dbtools.PageData;
import com.zretc.emptraining.entity.Dept;
import com.zretc.emptraining.entity.Emp;
import com.zretc.emptraining.entity.Teach;
import com.zretc.emptraining.entity.Users;
import com.zretc.emptraining.service.DeptService;
import com.zretc.emptraining.service.EmpService;
import com.zretc.emptraining.service.TeachService;
import com.zretc.emptraining.service.UsersService;
import com.zretc.emptraining.serviceimpl.DeptServiceImpl;
import com.zretc.emptraining.serviceimpl.EmpServiceImpl;
import com.zretc.emptraining.serviceimpl.TeachServiceImpl;
import com.zretc.emptraining.serviceimpl.UsersServiceImp;

/**
 * Servlet implementation class Emp
 */
@WebServlet("/EmpServlet")
public class EmpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 接口实例化
	EmpDao empDao = new EmpDaoImpl();
	EmpService empService = new EmpServiceImpl();
	UsersService userService = new UsersServiceImp();
	TeachService teacherService = new TeachServiceImpl();
	DeptService deptService = new DeptServiceImpl();
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public EmpServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1设置请求编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 标记当前为何种操作的变量
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}

		if ("".equals(op)) {
			// 分页查询
			doQuseryByPage(request, response);
		} else if ("del".equals(op)) {
			// 删除员工
			delEmp(request, response);
		} else if ("add".equals(op)) {
			// 添加员工
			addEmp(request, response);
		} else if ("updinfo".equals(op)) {
			// 修改信息
			updEmp(request, response);
		} else if ("updpic".equals(op)) {
			// 修改照片
			updPic(request, response);
		}  else if("getEmp".equals(op)) {
			// 根据编号获取员工信息
			getEmp(request, response);
		} else if("delAll".equals(op)) {
			// 批量删除
			delAll(request, response);
		} else if("ajaxReq".equals(op)) {
			// 获取员工列表
			ajaxReq(response);
		} else if ("getEmpByName".equals(op)) {
			doGetEmpName(request, response);
		} else if ("delEmpByName".equals(op)) {
			delEmpByName(request, response);
		} else if ("my".equals(op)) {
			//前台获取员工信息
			doGetEmpByqiantai(request, response);
		}else if ("dept".equals(op)) {
			//获取主管信息
			doGetEmpByDeptInfo(request, response);
		}
		else if ("upd1".equals(op)) {
			// 前台修改员工信息
			updSingleInfo(request, response);
		}
	}
	
	//前台修改员工信息

	private void updSingleInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String empName = request.getParameter("empName");
		String empAddress = request.getParameter("empAddress");
		String empEmail = request.getParameter("empEmail");
		String empPic = request.getParameter("empPic");			
		boolean flag = empService.updEmp(empName, empAddress, empEmail, empPic);
		System.out.println(flag);
		String msg = "修改成功";
		if (!flag) {
			msg = "修改失败";
		}
		Gson(msg, response);
	}
	
	public void delEmpByName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取员工信息
		String empName = "";
		if (request.getParameter("empName") != null) {
			empName = request.getParameter("empName");
		}
		// 调用 dao的方法
		boolean flag = empService.delEmpByName(empName);
		// 判断是否删除成功
		String msg = "删除成功";
		if (!flag) {
			//转发
			msg = "删除失败";
		}
		Gson(msg, response);
	}

	public void doGetEmpName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取员工信息
		String empName = "";
		if (request.getParameter("empName") != null) {
			empName = request.getParameter("empName");
		}
		// 调用 dao的方法
		List<Emp> list = (List<Emp>) empService.getEmpByName(empName);
		// 传递
		request.setAttribute("list", list);
		// 转发
		request.getRequestDispatcher("empadd.jsp").forward(request, response);
	}
	
	//前台获取员工信息
	public void doGetEmpByqiantai(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String empTel = "";
		if (request.getParameter("username") != null) {
			empTel = request.getParameter("username");
		}
		Emp emp= empDao.getEmpsByTel(empTel);
		// 4传递list给jsp
		request.setAttribute("emp", emp);
		System.out.println(emp);
		// 5 转发
		request.getRequestDispatcher("EmpInfo.jsp").forward(request, response);
		
	}
	//前台获取员工信息
		public void doGetEmpByDeptInfo(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			String empTel = "";
			if (request.getParameter("username") != null) {
				empTel = request.getParameter("username");
			}
			System.out.println(empTel);
			Emp emp= empDao.getEmpsByTel(empTel);
			// 4传递list给jsp
			request.setAttribute("emp", emp);
			System.out.println(emp);
			// 5 转发
			request.getRequestDispatcher("DeptInfo.jsp").forward(request, response);
			
		}
	
	private void ajaxReq(HttpServletResponse response) throws IOException {
		response.setContentType("application/json;charset=utf-8");
		List<Emp> list = empService.getEmp();
		Gson gson = new Gson();
		String jsonString = gson.toJson(list);
		PrintWriter out = response.getWriter();
		// 打印
		out.print(jsonString);
		// 关闭
		out.close();
	}

	private void updPic(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 修改照片
		int empNo = Integer.parseInt(request.getParameter("empNo"));
		System.out.println(empNo);
		String PicPath = "";
		String empPic = "";
		if(request.getAttribute("filename") != null) {
			PicPath = (String) request.getAttribute("filename");
			empPic = "upload/" + PicPath;
		}
		if(request.getAttribute("filename") == null){
			empPic = request.getParameter("empPic");
		}
		boolean flag = empService.updEmpPic(empNo, empPic);
		String jsonResponse = "{\"code\":1}";
		if(flag) {
			jsonResponse = "{\"code\":0}";
		}
		Gson(jsonResponse, response);
	}

	private void delAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String s = request.getParameter("r");
		String[] str = s.substring(0,s.length()-1).split(",");
		boolean flag = false;
		for (int i = 0; i < str.length; i++) {
			flag = empService.delEmp(Integer.parseInt(str[i]));
		}
		String msg = "删除失败!";
		if(flag) {
			msg = "删除成功!";
		}
		Gson(msg, response);
	}

	private void getEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int empNo = Integer.parseInt(request.getParameter("empNo"));
		String empPic = request.getParameter("empPic");
		List<Emp> list = empService.getEmpByEmpno(empNo);
		request.setAttribute("list", list);
		request.setAttribute("empPic", empPic);
		request.getRequestDispatcher("EmpUpd.jsp").forward(request, response);
	}
	/**
	 * 修改员工信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void updEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int empNo = Integer.parseInt(request.getParameter("empNo"));
		String empName = request.getParameter("empName");
		int deptNo = Integer.parseInt(request.getParameter("deptNo"));
		String empXl = request.getParameter("empXl");
		String empSex = request.getParameter("empSex");
		String empID = request.getParameter("empID");
		String Time = request.getParameter("empTime");
		System.out.println(Time);
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
		Date empTime = null;
		try {
			empTime = s.parse(Time);
			System.out.println(empTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String empAddress = request.getParameter("empAddress");
		String empTel = request.getParameter("empTel");
		String empEmail = request.getParameter("empEmail");
		String empJob = request.getParameter("empJob");
		
		if(empJob.equals("主管")) {
			// 先查看选择的部门是否有主管
			String deptName = deptService.getDeptnameByDeptno(deptNo);
			System.out.println(deptName);
			int en = deptService.getAllDept(deptName).get(0).getEmpNo();
			System.out.println(en);
			if(en != 0 && en != empNo) {
				// 如果没主管可添加
				String msg = "修改失败!该部门已经有主管!";
				Gson(msg, response);
			}else {
				// 如果有主管
				Emp emp = new Emp(empNo, empName, deptNo, empXl, empSex, empID, 
						empTime, empAddress, empTel, empEmail, empJob);
				boolean flag = empService.updEmp(emp);
				userService.updUserNo(empNo, empTel);
				String msg = "修改失败!";
				if (flag) {
					msg = "修改成功!";
				}
				Gson(msg, response);
			}
		}else {
			Emp emp = new Emp(empNo, empName, deptNo, empXl, empSex, empID, 
					empTime, empAddress, empTel, empEmail, empJob);
			boolean flag = empService.updEmp(emp);
			userService.updUserNo(empNo, empTel);
			String msg = "修改失败!";
			if (flag) {
				msg = "修改成功!";
			}
			Gson(msg, response);
		}
		
	}
	/**
	 * 分页查询员工信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void doQuseryByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 分页
		String keywords = "";
		// 获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		// 页码默认为1，记录数为10
		int page = 1;
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		PageData<Emp> pd = null;
		String selectKey = "员工名";
		if (request.getParameter("selectKey") != null) {
			selectKey = request.getParameter("selectKey");
		}
		if(selectKey.equals("员工名") || keywords.equals("")) {
			// 调用service方法
			pd = empService.getEmpByPage(page, pageSize, keywords);
		}else if(selectKey.equals("员工号")) {
			pd = empService.getEmpByPageEmpNo(page, pageSize, keywords);
		}else if(selectKey.equals("部门名")){
			pd = empService.getEmpByPageDeptName(page, pageSize, keywords);
		}else if(selectKey.equals("性别")) {
			pd = empService.getEmpByPageEmpSex(page, pageSize, keywords);
		}else if(selectKey.equals("学历")) {
			pd = empService.getEmpByPageEmpXl(page, pageSize, keywords);
		}
		
		// 传递
		request.setAttribute("pd", pd);
		request.setAttribute("selectKey", selectKey);
		// 转发回来的时候，将查询关键字存储在request范围内
		request.setAttribute("keywords", keywords);
		// 转发
		request.getRequestDispatcher("EmpList.jsp").forward(request, response);
		
	}
	/**
	 * 增加员工信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void addEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("到达增加页面");
		String empName = request.getParameter("empName");
		int deptNo = Integer.parseInt(request.getParameter("deptNo"));
		String empXl = request.getParameter("empXl");
		String empSex = request.getParameter("empSex");
		String empID = request.getParameter("empID");
		String empAddress = request.getParameter("empAddress");
		String empTel = request.getParameter("empTel");
		String empEmail = request.getParameter("empEmail");
		String empJob = request.getParameter("empJob");
		String PicPath = (String) request.getAttribute("filename");
		String empPic = "upload/" + PicPath;
		Emp emp = new Emp( 0 , empName, deptNo, empXl, empSex, empID, empAddress, empTel, empEmail, empJob,empPic);
		Users users = new Users(empTel, 0 , empTel, "123456", "1");
		String jsonResponse = "{\"code\":0}";
		if(empJob.equals("主管")){
			String deptName = deptService.getDeptnameByDeptno(deptNo);
			System.out.println(deptName);
			int en = deptService.getAllDept(deptName).get(0).getEmpNo();
			System.out.println(en);
			if(en != 0) {
				// 如果没主管可添加
				Gson(jsonResponse, response);
			}else {
				//事务执行
				boolean result = (Boolean) DBTools.transaction(new ITransaction() {
					@Override
					public Object execute(Connection conn) {
						boolean n1 = false, n2 = false;
						try {
							n1 = userService.addUsers(users);
							n2 = empService.addEmp(emp);
						} catch (Exception e) {
							throw new RuntimeException("操作失败，事务回滚!", e);
						}

						return n1&&n2;
					}
				});
				if(result) {
					int empNo = empService.getEmpnoByEmptel(empTel);
					userService.updUsersByName(empNo, empTel, "123456", empTel);
					Dept dept = new Dept(deptNo, deptName, empNo);
					boolean flag = deptService.updDept(dept);
					if(flag) {
						jsonResponse = "{\"code\":200}";
					}
				}
				Gson(jsonResponse, response);
			}
		}else {
			//事务执行
			boolean result = (Boolean) DBTools.transaction(new ITransaction() {
				@Override
				public Object execute(Connection conn) {
					boolean n1 = false, n2 = false;
					try {
						n1 = userService.addUsers(users);
						n2 = empService.addEmp(emp);
					} catch (Exception e) {
						throw new RuntimeException("操作失败，事务回滚!", e);
					}

					return n1&&n2;
				}
			});
			if(result) {
				int empNo = empService.getEmpnoByEmptel(empTel);
				userService.updUsersByName(empNo, empTel, "123456", empTel);
				if(empJob.equals("教员")) {
					Teach teach = new Teach(0, empName, empSex, empXl, empTel, "内部员工" , empPic);
					boolean f = teacherService.addTeach(teach);
					if(f) {
						jsonResponse = "{\"code\":200}";
					}
				}else {
					jsonResponse = "{\"code\":200}";
				}
			}
			Gson(jsonResponse, response);
		}
		
	}
	/**
	 * 删除员工信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void delEmp(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取员工信息
		int empNo = 0;
		if (request.getParameter("empNo") != null) {
			empNo = Integer.parseInt(request.getParameter("empNo"));
		}
		// 调用 dao的方法
		boolean flag = empService.delEmp(empNo);
		// 判断是否删除成功
		String msg = "删除成功";
		if (!flag) {
			//转发
			msg = "删除失败";
		}
		Gson(msg, response);
	}

	public void Gson(String keyword, HttpServletResponse response) throws IOException {
		Gson gson = new Gson();
		String toJson = gson.toJson(keyword);
		PrintWriter printWriter = response.getWriter();
		printWriter.print(toJson);
		printWriter.close();
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
